import { createApp } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import App from './App.vue';
import router from './router';

// 导入全局样式
import 'element-plus/dist/index.css';
import './assets/styles/global.css';

// 创建应用实例
const app = createApp(App);

// 创建 Pinia 实例
const pinia = createPinia();

// 注册所有 Element Plus 图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

// 全局错误处理
app.config.errorHandler = (err, vm, info) => {
  console.error('Vue Error:', err);
  console.error('Error Info:', info);
  // 可以在这里添加错误上报逻辑
};

// 全局警告处理
app.config.warnHandler = (msg, vm, trace) => {
  console.warn('Vue Warning:', msg);
  console.warn('Warning Trace:', trace);
  // 可以在这里添加警告处理逻辑
};

// 全局属性
app.config.globalProperties.$version = '1.0.0';
app.config.globalProperties.$env = process.env.NODE_ENV || 'development';

// 注册全局组件
// app.component('GlobalComponent', GlobalComponent);

// 注册全局指令
app.directive('focus', {
  mounted: (el) => el.focus()
});

app.directive('permission', {
  mounted: (el, binding) => {
    const { value } = binding;
    const authStore = useAuthStore();
    
    if (value && !authStore.hasPermission(value)) {
      el.parentNode?.removeChild(el);
    }
  }
});

// 注册全局过滤器
app.config.globalProperties.$filters = {
  formatDate: (value) => {
    if (!value) return '';
    const date = new Date(value);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  },
  formatNumber: (value) => {
    if (!value) return '0';
    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  }
};

// 使用插件
app.use(pinia);
app.use(router);
app.use(ElementPlus, {
  locale: zhCn,
  size: 'default',
  zIndex: 3000
});

// 环境配置
const isDevelopment = process.env.NODE_ENV === 'development';

if (isDevelopment) {
  app.config.performance = true;
  app.config.devtools = true;
} else {
  // 生产环境配置
  app.config.devtools = false;
  app.config.warnHandler = () => null;
  
  // 性能监控
  if (window.performance) {
    window.addEventListener('load', () => {
      const timing = window.performance.timing;
      const loadTime = timing.loadEventEnd - timing.navigationStart;
      console.log('Page Load Time:', loadTime);
    });
  }
}

// 挂载应用
app.mount('#app');

// 导出应用实例（用于测试）
export { app };